package com.sjtu.bookread.Fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sjtu.bookread.MainActivity;
import com.sjtu.bookread.R;
import com.sjtu.bookread.ReadPageActivity;
import com.sjtu.bookread.ReadPageActivity1;
import com.sjtu.bookread.control.DatabaseControl;
import com.sjtu.bookread.myRecyclerview.MyRecyclerViewAdapter;
import com.sjtu.bookread.myRecyclerview.MyViewHolder;
import com.sjtu.bookread.obj.BookListObj;
import com.sjtu.bookread.obj.BookObj1;
import com.sjtu.bookread.obj.ShelfBookObj;
import com.sjtu.bookread.service.RecomService;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import static com.sjtu.bookread.MainActivity.myBooks;

public class BookShelfFragment extends Fragment {
    // 视图
    View view;

    // Fragment中的RecycleView
    RecyclerView recyclerView;
    MyRecyclerViewAdapter<BookObj1> adapter;
    private ProgressBar progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout emptyLayout;

    private Handler mHandler = new Handler(Looper.getMainLooper()); //获取主线程的Handler

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_book_shelf, null);

        initBooks();

        setRecyclerView();

        return view;
    }

    //获取书籍数据
    private void initBooks() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BookListObj bookListObj = RecomService.getRecomService().getShelfBookList();
                if (bookListObj.isOk()) {
                    myBooks = bookListObj.getBooks();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter.refresh(myBooks);
                            progressBar.setVisibility(View.GONE);
                            //数据加载完毕时取消动画
                            swipeRefreshLayout.setRefreshing(false);
                            if (myBooks.isEmpty()) {
                                emptyLayout.setVisibility(View.VISIBLE);
                            }
                            else {
                                emptyLayout.setVisibility(View.GONE);
                            }

                            // Toast.makeText(getActivity(), "数据刷新完成", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    //设置页面的 RecyclerView
    private void setRecyclerView() {
        //获取页面控件
        recyclerView = view.findViewById(R.id.fragment_book_shelf_recyclerview);
        progressBar = view.findViewById(R.id.book_shelf_progressBar);
        emptyLayout = view.findViewById(R.id.shelf_linear_layout);
        emptyLayout.setVisibility(View.GONE);
        swipeRefreshLayout = view.findViewById(R.id.book_shelf_swipeRefresh);

        //设置 RecyclerView 的布局方式
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        //设置 RecycleAdapter
        adapter = new MyRecyclerViewAdapter<BookObj1>(getActivity(), R.layout.item_book, myBooks) {
            @Override
            public void convert(MyViewHolder holder, BookObj1 bookObj1) {
                // 书名
                TextView bookName = holder.getView(R.id.item_book_name);
                bookName.setText(bookObj1.getTitle());
                // 封面 通过网络获取
                final ImageView imageView = holder.getView(R.id.item_book_cover);
                final String iconURL = RecomService.ApiUrl + "/"+ bookObj1.getCover();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL(iconURL);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setConnectTimeout(10000);
                            if (connection.getResponseCode() == 200) {
                                InputStream inputStream = connection.getInputStream();
                                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        imageView.setImageBitmap(bitmap);
                                    }
                                });
                        }
                    } catch (Exception e) {
                            System.err.println(e.getMessage());
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    imageView.setImageDrawable(getResources().getDrawable(R.mipmap.bookcover));
                                }
                            });
                        }
                    }
                }).start();
                // 作者
                TextView author = holder.getView(R.id.item_book_author);
                author.setText(bookObj1.getAuthor());
                // 类型
                TextView major = holder.getView(R.id.item_book_type);
                major.setText(bookObj1.getCate());
                // 简介
                TextView intro = holder.getView(R.id.item_book_intro);
                String str = bookObj1.getShortIntro();
                if (str.length() > 50) str = str.substring(0, 50);
                str += "...";
                intro.setText(str);
            }
        };

        adapter.refresh(myBooks);
        adapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(getActivity(), ReadPageActivity1.class);
                Bundle bundle = new Bundle();
                bundle.putInt("bookid", myBooks.get(position).getId());
                bundle.putString("bookname", myBooks.get(position).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onLongClick(final int position) {
                // 长按弹出对话框
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setMessage("确定要从书架移除" + myBooks.get(position).getTitle() + "吗？");
                dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RecomService.getRecomService().adddelShelfbook(0,myBooks.get(position).getId());
                                initBooks();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        setRecyclerView();
                                    }
                                });
                            }
                        }).start();
                    }
                });
                dialog.show();
            }
        });

        recyclerView.setAdapter(adapter);

        //设置下拉显示的动画颜色
        swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
        //下拉刷新的回调事件
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //数据刷新
                initBooks();
            }
        });
    }
}
